<script setup>
import { useUrl } from '~~/composables/states';
import { storeToRefs } from 'pinia';
import dayjs from 'dayjs';

const mpp = useCookie('mpp');
const fio_short = useCookie('fio_short');
const access_list = useCookie('access_list');
const access = access_list.value;
const isOpen = ref(false)
const counter = useStoreCounter();

const count_rasp = computed(() => counter.count_rasp);
const containerStore = useContainerSearsh();
const { container } = storeToRefs(containerStore);
const { setContainer } = containerStore;
// const container = ref("")
const container_response = ref({})
const urlHome = useUrl()
const container_show = ref('none')

const conteinerDescription = ref('')
const naryadNumber = ref('')

const toast = useToast()

function logout() {

    const authCookie = useCookie('user')
    authCookie.value = null
    const mppCookie = useCookie('mpp')
    mppCookie.value = null
    const fio_shortCookie = useCookie('fio_short')
    fio_shortCookie.value = null
    const access_listCookie = useCookie('access_list')
    access_listCookie.value = null
    const dolzhCookie = useCookie('dolzh')
    dolzhCookie.value = null
    return navigateTo('/login');
}

function refresh_all() {
    // refreshNuxtData()
    location.reload();
    // console.log("reloaded")
}

async function hide() {
    container_show.value = "";
    // container.value = "";
    setContainer("");
}

async function get_conteiner_info() {
    if (container.value == 0 || container.value == '') {
        return
    };
    const { data: container_info } = await useLazyFetch(urlHome.value + 'naryad/container_info/' + container.value + '/')
    console.log(container_info.value)
    if (container_info.value !== null) {
        container_show.value = container_info.value.used
    } else {
        container_show.value = false
    }
    console.log(container_show.value)
    container_response.value = container_info.value
    if (container_show.value === true) {
        conteinerDescription.value = `Наряд <b>${container_response.value.info[0].nkv}</b>. Врач ${container_response.value.info[0].naryad_doc__user__fam} ${container_response.value.info[0].naryad_doc__user__im[0]} ${container_response.value.info[0].naryad_doc__user__ot[0]}. Наряд на этапе у ${container_response.value.info[0].user_etap_link__fam} ${container_response.value.info[0].user_etap_link__im[0]} ${container_response.value.info[0].user_etap_link__ot[0]} Стоимость <b>${container_response.value.info[0].stu}</b> Пациент ${container_response.value.info[0].patient__fam} ${container_response.value.info[0].patient__im[0]} ${container_response.value.info[0].patient__ot[0]}`
        toast.add({ title: `<b>Контейнер №${container.value} занят</b>`, id: container_response.value.info[0].nkv, description: conteinerDescription.value, color: "yellow", icon: "i-heroicons-check-badge" })
    } else if (container_show.value === false) {
        toast.add({ title: `<b>Контейнер №${container.value} свободен</b>`, description: 'Вы можете использовать этот контейнер', icon: "i-heroicons-check-badge" })
    }
    return;
}

async function getNaryadInfo() {
    const response = await $fetch(`${urlHome.value}lab/naryad_info/`, {
        query: {
            naryad: naryadNumber.value,
        }
    })
    if (response.status === 200) {
        console.log(response)
        console.log("success")
        // toast.add({ title: `<b>Контейнер №${container.value} занят</b>`, id: container_response.value.info[0].nkv, description: conteinerDescription.value, color: "yellow", icon: "i-heroicons-check-badge" })
        toast.add({ title: `<b>Наряд №${response.data.nkv} на этапе у ${response.data.user_etap_link.fam}. Врач ${response.data.naryad_doc.user.fam}</b>`, id: response.data.nkv, description: `на сумму ${response.data.stu} от ${dayjs(response.data.dou).format('DD.MM.YYYY')} ${response.data.dzr ? 'наряд закрыт ' + dayjs(response.data.dzr).format('DD.MM.YYYY') : 'наряд не закрыт'}`, color: "yellow", icon: "i-heroicons-check-badge" })
    } else {
        toast.add({ title: `<b>Наряд №${naryadNumber.value} не найден</b>`, id: naryadNumber.value, description: ``, color: "yellow", icon: "i-heroicons-check-badge" })
        console.log("error")
    }

    if (container_show.value === true) {
        conteinerDescription.value = `Наряд <b>${container_response.value.info[0].nkv}</b>. Врач ${container_response.value.info[0].naryad_doc__user__fam} ${container_response.value.info[0].naryad_doc__user__im[0]} ${container_response.value.info[0].naryad_doc__user__ot[0]}. Наряд на этапе у ${container_response.value.info[0].user_etap_link__fam} ${container_response.value.info[0].user_etap_link__im[0]} ${container_response.value.info[0].user_etap_link__ot[0]} Стоимость <b>${container_response.value.info[0].stu}</b> Пациент ${container_response.value.info[0].patient__fam} ${container_response.value.info[0].patient__im[0]} ${container_response.value.info[0].patient__ot[0]}`
        toast.add({ title: `<b>Контейнер №${container.value} занят</b>`, id: container_response.value.info[0].nkv, description: conteinerDescription.value, color: "yellow", icon: "i-heroicons-check-badge" })
    } else if (container_show.value === false) {
        toast.add({ title: `<b>Контейнер №${container.value} свободен</b>`, description: 'Вы можете использовать этот контейнер', icon: "i-heroicons-check-badge" })
    }
    return;
}

function sleep(ms) {
    return new Promise(res => setTimeout(res, ms));
}

defineShortcuts({
    meta_l: {
        usingInput: true,
        handler: () => { navigateTo('/login') }
    }
})

</script>

<template>
    <div>
        <header>
            <slot name="header">
                <div class="flex">
                    <!-- <div class=""> -->
                    <div class="flex-1">
                        <!-- <div class=""> -->
                        <a class="btn btn-ghost normal-case text-xl" @click="refresh_all">{{ fio_short }}</a>
                    </div>
                    <div class="flex flex-nowrap px-2 pt-2">
                        <div class="mx-2 pr-2 glow-on-hover">
                            <NuxtLink to="/lab/naryad_list">
                                <UButton icon="i-heroicons-exclamation-circle" />
                            </NuxtLink>
                        </div>

                        <div class="mx-2 pr-2 glow-on-hover">
                            <NuxtLink to="/lab/waitlist">
                                <UButton icon="i-heroicons-clock" />
                            </NuxtLink>
                        </div>

                        <div v-if="access == 'tech_st'" class="mx-2 pr-2 glow-on-hover">
                            <label tabindex="0" class="btn btn-ghost btn-circle">
                                <div class="indicator">
                                    <NuxtLink to="/lab/stlist">
                                        <UButton icon="i-heroicons-square-3-stack-3d" />
                                    </NuxtLink>
                                </div>
                            </label>
                        </div>
                        <div v-if="access == 'tech_st'" class="mx-2 pr-2 glow-on-hover">
                            <label tabindex="1" class="btn btn-ghost btn-circle">
                                <div class="indicator">
                                    <NuxtLink to="/lab/report_st">
                                        <UButton icon="i-heroicons-clipboard-document-list" />
                                    </NuxtLink>
                                </div>
                            </label>
                        </div>
                        <div v-if="access == 'doc' || access == 'zav_ort'" class="mx-2 pr-2 glow-on-hover">
                            <label tabindex="0" class="btn btn-ghost btn-circle">
                                <div class="indicator">
                                    <NuxtLink to="/lab/report/month/doctor">
                                        <UButton icon="i-heroicons-clipboard-document-list" />
                                    </NuxtLink>
                                </div>
                            </label>
                        </div>
                        <div v-if="access == 'zav_ort'" class="mx-2 pr-2 glow-on-hover">
                            <label tabindex="0" class="btn btn-ghost btn-circle">
                                <div class="indicator">
                                    <NuxtLink to="/lab/report_zav">
                                        <UButton icon="i-heroicons-square-3-stack-3d" />
                                    </NuxtLink>
                                </div>
                            </label>
                        </div>
                        <div v-if="access == 'zav_ort'" class="mx-2 pr-2 glow-on-hover">
                            <label tabindex="0" class="btn btn-ghost btn-circle">
                                <div class="indicator">
                                    <UButton icon="i-heroicons-document-chart-bar" @click="isOpen = true" />
                                </div>
                            </label>
                        </div>
                        <div class="mx-2 pr-2 glow-on-hover">
                            <UButton icon="i-heroicons-power" @click="logout()" />
                        </div>
                    </div>
                </div>
                <div
                    class="px-2 grid grid-cols-4 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-3 sm:flex md:flex lg:flex xl:flex 2xl:flex sm:gap-4">
                    <UInput placeholder="Номер контейнера" v-model.number="container"
                        @keypress.enter="get_conteiner_info" size="sm" icon="i-heroicons-magnifying-glass-20-solid"
                        color="green" trailing />
                    <UButton label="X" v-if="container_show === true || container_show === false" @click="hide" />
                    <UInput placeholder="Поиск по номеру наряда" v-model.number="naryadNumber"
                        @keypress.enter="getNaryadInfo" size="sm" icon="i-heroicons-magnifying-glass-20-solid"
                        color="green" trailing />
                    <UButton label="X" v-if="container_show === true || container_show === false" @click="hide" />
                </div>
                <div
                    class="px-2 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-3 sm:flex md:flex lg:flex xl:flex 2xl:flex sm:gap-4">

                </div>
                <UNotifications>
                    <template #title="{ title }">
                        <span v-html="title" />
                    </template>
                    <template #description="{ description }">
                        <span v-html="description" />
                    </template>
                </UNotifications>
            </slot>
        </header>
        <USlideover v-model="isOpen">
            <div class="p-4 flex-1">
                <div class="grid grid-col-1">
                    <!-- <NuxtLink to="/lab/report_lgot">
                        <UButton @click="isOpen = false" variant="ghost">Отчет по открытым льготным нарядам</UButton>
                    </NuxtLink> -->
                    <NuxtLink to="/lab/report/open_naryads">
                        <UButton @click="isOpen = false" variant="ghost">Отчет по открытым нарядам</UButton>
                    </NuxtLink>
                    <!-- <NuxtLink to="/lab/report/close_naryads">
                        <UButton @click="isOpen = false" variant="ghost">Отчет по закрытым нарядам</UButton>
                    </NuxtLink> -->
                </div>
            </div>
        </USlideover>
        <main>
            <slot />
        </main>
    </div>
</template>

<style>
.glow-on-hover {
    width: 30px;
    height: 30px;
    border: none;
    outline: none;
    color: #fff;
    background: #ffffff;
    cursor: pointer;
    position: relative;
    z-index: 0;
    border-radius: 10px;
}

.glow-on-hover:before {
    content: '';
    background: linear-gradient(45deg, #ff0000, #ff7300, #fffb00, #48ff00, #00ffd5, #002bff, #7a00ff, #ff00c8, #ff0000);
    position: absolute;
    top: -2px;
    left: -2px;
    background-size: 400%;
    z-index: -1;
    filter: blur(5px);
    width: calc(100% + 4px);
    height: calc(100% + 4px);
    animation: glowing 20s linear infinite;
    opacity: 0;
    transition: opacity .3s ease-in-out;
    border-radius: 10px;
}

.glow-on-hover:active {
    color: #ffffff
}

.glow-on-hover:active:after {
    background: transparent;
}

.glow-on-hover:hover:before {
    opacity: 1;
}

.glow-on-hover:after {
    z-index: -1;
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    background: #ffffff;
    left: 0;
    top: 0;
    border-radius: 10px;
}

@keyframes glowing {
    0% {
        background-position: 0 0;
    }

    50% {
        background-position: 400% 0;
    }

    100% {
        background-position: 0 0;
    }
}
</style>